Program to print numbers from 1 to n using While loop, Do while loop and For loop.| Using C language| C Program series 14|
👨💻Program to print numbers from 1 to n using the While loop, Do while loop, and For loop.
1. While loop
Code:
//Program to print numbers from 1 to n using a while loop.
#include<stdio.h>
main()
{
printf("Program to print numbers from 1 to n using while loop.\n\n");
int i=1,n;
printf("Enter the value of n :");
scanf("%d",&n);
while(i<=n)//loop will run upto given condition true.
{
printf("%d\n",i);
i++;//here,this line perform i=i+1
}
/*NOTE:
In a while loop, The loop first checks the condition then executes every time.
So, while the loop is executed, if a given condition is true.
while loop is NOT executed, if a given condition is NOT true.
*/
}
2. Do While loop
Code:
//Program to print numbers from 1 to n using do-while-loop.
#include<stdio.h>
main()
{
printf("Program to print numbers from 1 to n using do-while-loop.\n\n");
int i=1,n;
printf("Enter the value of n :");
scanf("%d",&n);
do
{
printf("%d\n",i);
i++;//here,this line perform i=i+1
}while(i<=n);
//loop will run up to given condition true.
/*NOTE:
In do a while loop, The loop is executed and then checks the condition every time.
So, do while loop is executed at least one-time either given condition is true or false.
*/
}
3. For loop
Code:
//Program to print numbers from 1 to n using for-loop.
#include<stdio.h>
main()
{
printf("Program to print numbers from 1 to n using for-loop.\n\n");
int i,n;
printf("Enter the value of n :");
scanf("%d",&n);
//loop will run up to the given condition true.
for(i=1;i<=n;i++)//syntax: for( initialization; condition; increment or decrement)
{
printf("%d\n",i);
}
/*NOTE:
In for-loop, The loop first checks the condition and then executes every time.
So,for-loop is executed, if a given condition is true.
for-loop is NOT executed, if a given condition is NOT true.
*/
}
Output same for all :
Comments
Post a Comment